package com.listener;

import com.zjs.mapper.SysUserMapper;
import com.zjs.pojo.SysUser;
import com.zjs.pojo.SysUserExample;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpCookie;
import java.util.List;

/**
 * @类名： LoginInterceptor
 * @说明： TODO
 * @作者：SS 苏帅出品
 * @时间：2019/12/16 20:39
 * @版本：1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    SysUserMapper sysUserMapper;


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {


        //如果请求路径是登录验证路径则 放行

        if (httpServletRequest.getRequestURI().contains("/sysUser/login.action")) {


            return true;


        }


        //清除msg提示消息
        httpServletRequest.removeAttribute("msg");


        // 如果登录成功后 Principal 中存储的是 SysUser对象
        Subject subject = SecurityUtils.getSubject();

        SysUser principal = (SysUser) subject.getPrincipal();

        //得到浏览器的sessionId
        String id = httpServletRequest.getSession().getId();

        //得到姓名
        String username = principal.getUsername();

        //创建user
        SysUser user = new SysUser();
        user.setIsLogin(id);
        user.setUsername(username);

        //通过user对象查找

        SysUser user1 = sysUserMapper.selectByIsLogin(user);

       //如果返回不为null 则表示验证的 sessioId 和数据库中存储的一致 则返回true 继续执行
        if (user1 != null) {

            return true;

        }

        //设置提示信息
        httpServletRequest.setAttribute("msg", "异地登录,请重新登录!");

        //跳转到登录页面
        httpServletRequest.getRequestDispatcher("/login.jsp").forward(httpServletRequest, httpServletResponse);


        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
